package cn.wenhe9.yygh.cmn.service.impl;

import cn.wenhe9.yygh.cmn.listener.DictListener;
import cn.wenhe9.yygh.cmn.mapper.DictMapper;
import cn.wenhe9.yygh.cmn.service.DictService;
import cn.wenhe9.yygh.common.utils.RedisCache;
import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.model.cmn.Dict;
import cn.wenhe9.yygh.model.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DuJinliang
 * 2022/2/15
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private RedisCache redisCache;

    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = this.query().eq("parent_id", id).list();

            if (!dictList.isEmpty()){
                for (Dict dict : dictList) {
                    Long dictId = dict.getId();
                    List<Dict> childrenList = this.query().eq("parent_id", dictId).list();
                    dict.setHasChildren(!childrenList.isEmpty());
                }

            }

        return dictList;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        //查询数据库
        List<Dict> dictList = this.list();

        List<DictEeVo> voList = dictList.stream().map(dict -> new DictEeVo(dict)).collect(Collectors.toList());
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(voList);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict")
    public ResultResponse importDict(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
            return ResultResponse.ok();
        }catch (IOException e){
            e.printStackTrace();
            return ResultResponse.fail();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(dictCode)){
            Dict dict = this.getDictByDictCode(dictCode);

            Long parentId = dict.getId();

            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parentId)
                    .eq("value", value));

            if (finalDict != null){
                return finalDict.getName();
            }

            return "";
        }
        queryWrapper.eq("value", value);

        Dict dict = baseMapper.selectOne(queryWrapper);

        if (dict != null){
            return dict.getName();
        }

        return "";
    }

    @Override
    public ResultResponse findByDictCode(String dictCode) {
        //根据dictCode获取对应的id
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);

        if (dict == null){
            throw new RuntimeException("未找到对应的dict_code");
        }

        //再根据id获取相应的子节点
        Long id = dict.getId();
        List<Dict> dictList = this.query().eq("parent_id", id).list();

        return ResultResponse.ok(dictList);
    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        return baseMapper.selectOne(queryWrapper);
    }
}
